<?php

namespace app\home\controller;

use app\home\model\Idfa724Model;
use app\home\model\Order;
use app\home\service\NotifyService;
use app\home\service\OrderService;
use think\Db;
use think\helper\hash\Md5;
use think\Model;
use think\Request;
use think\response\Json;

class Pay800016 extends BasePay
{

    const appSecret = "uEW1otdcj2u0EUYKerjY6g==";
    const appId = "2882303761522193486";
    const packageName = "com.hmgame.cafishing.mi";
    public function __construct()
    {
        header('Content-Type: text/html;charset=utf-8');
        header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
        header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); // 允许请求的类型
        header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
        header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin'); // 
    }

    public function log()
    {

        $res = $this->consume('PID240119101937674289392311728142','ID','1002');
        var_dump($res);die;
        die;
        $nonce = 'htma' . time();
        $url = "https://rest-iap.miglobalpay.com";
        $p = '/ID/developer/v1/applications/com.hmgame.cafishing.mi/purchases/products/9025/tokens/PID240118151034997289392311728142';
        $signStr = "GET\n\napplication/json\n\nx-ias-sign-nonce:" . $nonce . "\n" . $p;

        $appSecret = 'uEW1otdcj2u0EUYKerjY6g==';


        $signResult = base64_encode(hash_hmac('sha1', $signStr, $appSecret, true));

        //  var_dump($signResult);die; // 结果 NTWaaiIjtoerWdM0h2oC5XwlTTM=

        $header = array(
            'appId: 2882303761522193486',
            'timestamp: ' . time(),
            'x-ias-sign-nonce: ' . $nonce,
            'signType:SHA512',
            'Content-type: application/json',
            'Authorization: ias ' . $signResult
        );
        $obj = $this->curl($url . $p, $header);
    }

    public function order()
    {
        parent::order();
        $data_Arr['code'] = 'success';
        $params = Request::instance()->param();

        $return['orderId'] = $this->order_array['id'];
        $return['money'] = $this->order_array['amount'];
        $return['productName'] = $this->order_array['goods_name'];
        $return['stroeid'] = self::STR . $params['stroeid'];

        exit(json_encode(['code' => 1, 'msg' => '', 'data' => $return]));
    }


    public function notify()
    {

        $params = Request::instance()->param();
        mylog($params);
        try {
            $res = json_decode(base64_decode($params['message']['data']), true);
            $tokens = $res['oneTimeProductNotification']['purchaseToken'];
            $region = substr($tokens, 1, 2);
            $products = $res['oneTimeProductNotification']['sku'];

            //查询订单
            $Res = $this->getOrder($tokens,$region,$products);
            $order = json_decode($Res,true);
            //是否购买
            if($order['purchaseState'] !=0){
                throw new \Exception('purchaseState false');
            }
            //已经消耗的不发货
            // if($order['consumptionState'] ==1){
            //     throw new \Exception('consumptionState false');
            // }
            // //消耗购买 走客户端
            // $this->consume($tokens,$region,$products);

            //保存第三方单号
            $tradeLog = (new \app\home\model\TradeLog)->where(['id' => $order['obfuscatedExternalProfileId']])->find();
            if (empty($tradeLog)) {
                throw new \Exception('订单不存在');
            }
            $tradeLog->transactionID = $order['orderId'];
            $tradeLog->save();

            if ($tradeLog['goods_id'] != $order['productId']) {
                throw new \Exception('计费点不一致');
            }

            if ($tradeLog["status"] == OrderService::PAY_STATUS_PAID) {
                mylog("Pay800016 订单已经处理过了 订单id" . $tradeLog['id']);
                exit('SUCCESS');
            }

            //发货
            $notifyService = new NotifyService();
            if ($notifyService->notifyProcess($tradeLog) == false) {
                throw new \Exception('notifyProcess false');
            }
            exit('SUCCESS');
        } catch (\Exception $exception) {
            mylog('Pay800016-error:' . $exception->getMessage() . ' line:' . $exception->getLine() . ' file:' . $exception->getFile());
            exit('FAIL');
        }
    }

    public function getOrder($tokens,$region,$products)
    {
        $nonce = 'getorder' . time();
        $url = "https://rest-iap.miglobalpay.com";
        $p = '/' . $region . '/developer/v1/applications/' . self::packageName . '/purchases/products/' . $products . '/tokens/' . $tokens;
        $signStr = "GET\n\napplication/json\n\nx-ias-sign-nonce:" . $nonce . "\n" . $p;

        $appSecret = self::appSecret;
        $signResult = base64_encode(hash_hmac('sha1', $signStr, $appSecret, true));

        $header = array(
            'appId: ' . self::appId,
            'timestamp: ' . time(),
            'x-ias-sign-nonce: ' . $nonce,
            'Content-type: application/json',
            'Authorization: ias ' . $signResult
        );
        $obj = $this->curl($url . $p, $header);
        return $obj;
    }
    protected function curl($url, $heder)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $heder);
        //TODO 证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $response = curl_exec($ch);

        curl_close($ch);
        mylog($response);
        return $response;
    }

    public function consume($region,$products,$tokens)
    {
        $url = "https://rest-iap.miglobalpay.com";
        $nonce = 'consume' . time();
        $p = '/' . $region . '/developer/v1/applications/' . self::packageName . '/purchases/products/' . $products . '/tokens/' . $tokens . ':consume';
        $signStr = "POST\n\napplication/json\n\nx-ias-sign-nonce:" . $nonce . "\n" . $p;

        $appSecret = self::appSecret;
        $signResult = base64_encode(hash_hmac('sha1', $signStr, $appSecret, true));

        $header = array(
            'appId: ' . self::appId,
            'timestamp: ' . time(),
            'x-ias-sign-nonce: ' . $nonce,
            'Content-type: application/json',
            'Authorization: ias ' . $signResult
        );

        $res = $this->post($url . $p, $header);
        return true;

        if($res != 200){
            return false;
        }
        return true;
    }
    /**
     * @param $url
     * @param null $body
     * @return bool|string
     * @throws Exception
     */
    protected function post($url, $head)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $head);
        curl_setopt($ch, CURLOPT_POST, true);
        //TODO 证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $response = curl_exec($ch);
        curl_close($ch);
        mylog($response);
        var_dump($response);die;
        return $response;
    }
}
